<template>
  <el-container class="tab-container-select">
    <el-dialog title="选择人员" :width="width" :visible.sync="visiableDialog" @opened="getTreeAndTableData" @close="cancelAction">
      <el-container>
        <el-aside width="auto" class="aside">
          <el-tag>当前机构：{{ organizationName }}</el-tag>
          <el-scrollbar
            style="height:300px;"
          >
            <el-tree ref="tree" class="aside-tree" :data="treeData" node-key="id" :default-expanded-keys="cacheTreeExpandedKeys" @current-change="handleTreeSelectChange" />
          </el-scrollbar>
        </el-aside>
        <el-main>
          <el-form label-width="80px" style="margin: 20px">
            <el-form-item label="人员列表">
              <el-transfer
                v-model="userList"
                :titles="['待选择人员', '已选择人员']"
                filterable
                :filter-method="filter"
                filter-placeholder="请输入员工姓名"
                :data="options"
                :props="{
                  key: 'id',
                  label: 'nameOfAccount'
                }"
                @change="change"
              />
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
      <el-footer style="margin-top:30px;padding:0px">
        <el-button type="primary" style="float:right;" @click="confirmAction">确认</el-button>
        <el-button type="default" style="float:right;margin-right:10px;" @click="cancelAction">取消</el-button>
      </el-footer>
    </el-dialog>
  </el-container>
</template>

<script>
import { getExpandedTreeNodeId } from '@/utils/tree'
export default {
  name: 'TransferUser',
  // 设置绑定参数
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: {
      type: Array,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '1000px'
    },
    treeRoot: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      options: [],
      optionsAll: this.value,
      loading: false,
      visiableDialog: this.visible,
      treeData: [],
      cacheTreeExpandedKeys: [this.constant.DEFAULT_EXPANDED_ID],
      userList: this.value.map(i => i.id),
      userSelectList: this.value,
      organizationName: '',
      queryCondition: {
        organizationId: ''
      }
    }
  },
  watch: {
    visiableDialog(val) {
      this.$emit('update:visible', val)
    },
    visible(val) {
      this.visiableDialog = val
    },
    value() {
      this.optionsAll = this.value
      this.userList = this.value.map(i => i.id)
      this.userSelectList = this.value
    }
  },
  methods: {
    filter(query, item) {
      if (!item.nameOfAccount) {
        item.nameOfAccount = item.name + '(' + item.account + ')'
      }
      return item.nameOfAccount.indexOf(query) > -1
    },
    getUserList() {
      this.loading = true
      this.$api.system.user.getUserList(this.queryCondition)
        .then(res => {
          if (res.status === this.constant.REQUEST_SUCCESS) {
            if (res.data) {
              this.options = res.data
            } else {
              this.options = []
            }
            // 储存所有的用户信息optionsAll
            this.optionsAll = this.optionsAll.concat(this.options)
            // 过滤出已选的用户信息，添加到新的选项中
            const list = this.optionsAll.filter(i => {
              return this.userList.includes(i.id)
            })
            // 去重
            const obj = {}
            this.options = this.options.concat(list).reduce(
              function(item, next) {
                obj[next.id] ? '' : obj[next.id] = true && item.push(next)
                return item
              }, []
            )
          }
        }).finally(() => {
          this.loading = false
        })
    },
    cancelAction() {
      this.visiableDialog = false
    },
    confirmAction() {
      this.$emit('input', this.userSelectList)
      this.visiableDialog = false
    },
    getTreeAndTableData() {
      // 在刷新树之前，记录一下树展开状态，以便刷新数据后恢复为原展开状态
      this.cacheTreeExpandedKeys = getExpandedTreeNodeId(this.$refs.tree)
      if (!this.cacheTreeExpandedKeys || this.cacheTreeExpandedKeys.length === 0) {
        this.cacheTreeExpandedKeys = [this.constant.DEFAULT_EXPANDED_ID]
      }
      this.$api.system.organization.persentOrganizationTree({ id: this.treeRoot })
        .then(res => {
          if (res.status === this.constant.REQUEST_SUCCESS) {
            this.treeData = res.data
            // 如没有默认选中节点
            if (this.queryCondition.organizationId === '') {
              // 默认设置根节点
              this.queryCondition.organizationId = this.treeData[0].id
              this.organizationName = this.treeData[0].label
            }
            this.getUserList()
          }
        })
    },
    handleTreeSelectChange(data) {
      this.queryCondition.organizationId = data.id
      this.organizationName = data.label
      this.getUserList()
    },
    change(val) {
      const result = []
      for (const value of val) {
        const obj = this.optionsAll.find((item) => {
          return item.id === value
        })
        result.push(obj)
      }
      this.userSelectList = result
    }
  }
}
</script>
<style lang="scss" scoped>
.tab-container-select{
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .el-dialog__body{
    .el-main{
      .el-form{
        margin: 0px
      }
       padding: 0px
    }
    padding: 1px 20px
  }
}
</style>
<style lang="scss" scoped>
.tab-container-select{
  .aside{
    min-width: 20%;
    background-color: white;
  }
}
</style>
